package com.shop.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ShearCaptcha;
import com.shop.pojo.Admin;
import com.shop.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/admin")
public class AdminAction {
//    发送验证码

    @RequestMapping("/code")
    public void code(HttpServletRequest request, HttpServletResponse response) {
//        防止浏览器缓存
        //防止浏览器缓存验证码
        response.setDateHeader("Expires", -1);
        response.setHeader("Cache-Control", "no-Cache");
        response.setHeader("pragma", "no-Cache");
        //定义图形验证码的长、宽、验证码字符数、干扰线宽度
        ShearCaptcha captcha = CaptchaUtil.createShearCaptcha(100, 40, 4, 4);
        String code = captcha.getCode();
//        将正确的生成的数字保存在session中
        request.getSession().setAttribute("codes", code);

        try {
            ServletOutputStream out = response.getOutputStream();
            captcha.write(out);
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
//    检查验证码
    @RequestMapping(value = "checkCode.action",produces = "text/html;charset=utf-8")
   @ResponseBody
    public String chekCode(String jsp_code, HttpServletRequest request, HttpServletResponse response) {
        Object codes = request.getSession().getAttribute("codes");
        if (codes == null || !codes.equals(jsp_code)) {
                return "验证码不正确";
        }else {
            return "";
        }

    }
//    用户登录
    @Autowired
    private AdminService adminService;
    @RequestMapping(value = "login.action", produces = "text/html;charset=utf-8")
    public String checkLogin(String name, String pwd, HttpServletRequest request) {
        Admin login = this.adminService.login(name, pwd);
        if (login != null ) {
//            存储到session中，判断是否登录
            request.getSession().setAttribute("admin", login);

            return "forward:/admin/main.jsp";
        } else {
            request.setAttribute("errmsg","用户名或密码错误");
            return "forward:/admin/login.jsp";
        }
    }

}
